package com.bsmyl.lottery.Service.impl;

import com.alibaba.fastjson.JSON;
import com.bsmyl.lottery.Service.LotteryService;
import com.bsmyl.lottery.core.Tess4JUtils;
import com.bsmyl.lottery.feign.LotteryLoginClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * describe:
 *
 * @author LiuWenPing
 * @date 2019/03/05
 */

@Service
public class LotteryServiceImpl implements LotteryService {
    private static final Logger LOGGER = LoggerFactory.getLogger(LotteryServiceImpl.class);

    private final String PA = "captcha.next";

    private final String KEY = "66954091";

    @Autowired
    private LotteryLoginClient lotteryLoginClient;

    @Override
    public void login() {
        String code = null;
        while (code==null||code.length() != 4) {
            code = getCode(PA, KEY);
        }
        LOGGER.info("code:"+code+",lenght:"+code.length());
        //构造参数
        String json = getParam(code);
        Map<String, Object> res = JSON.parseObject(lotteryLoginClient.login(json),Map.class);
        if (res.get("result").equals("0")) {
            login();
            return;
        }
        Map<String, Object> result = (Map<String, Object>) res.get("result");
        //登陆成功,保存sessionId
        saveToken(result);


    }

    private void saveToken(Map<String,Object> map) {

        String token = map.get("sessionId").toString();
        if (token != null) {
            IssueServiceImpl.token = token;
        }
        LOGGER.info("登陆成功");
    }

    public String getParam(String code){
        Map<String, Object> loginParam = new HashMap<>();
        loginParam.put("id", "51753789666579");
        loginParam.put("jsonrpc", "2.0");
        loginParam.put("method", "auth.trial.login");

        Map<String, Object> params = new HashMap<>();
        params.put("sn", "ur00");
        params.put("captchaKey", KEY);
        params.put("captchaCode", code);
        params.put("terminal", 1);
        loginParam.put("params", params);
        String json = JSON.toJSONString(loginParam);
        //打印参数
        LOGGER.info("参数:"+json);
        return json;
    }

    public String getCode(String pa,String key){
        byte[] codeBytes = lotteryLoginClient.getCode(pa,key);
        String code = Tess4JUtils.discernCode(codeBytes).replaceAll("\r|\n", "");;
        return code;
    }

    //@PostConstruct
    private void initLogin(){
        login();
    }
}
